package cn.yunhe.shiro;

import cn.yunhe.entity.Role;
import cn.yunhe.entity.User;
import cn.yunhe.service.MenuItemService;
import cn.yunhe.service.RoleService;
import cn.yunhe.service.UserService;
import cn.yunhe.util.SpringContextUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.List;

/**
 * shiro realm 认证授权
 *
 * @author Administrator
 */
//@Configuration

public class ShiroRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;//用户登录表
    @Resource
    private RoleService roleService;//角色表
    @Resource
    private MenuItemService menuItemService; //权限表


    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("---------进入授权---------");
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        try {
            String usercode= (String) principals.getPrimaryPrincipal();
            User user= userService.userLogin(usercode);
            Integer uid= user.getUserId();
            Role role = roleService.getUserRole(uid);
            List<String> userRoles = menuItemService.getUserMenu(role.getId());
            info.addStringPermissions(userRoles);
        }catch (Exception e){
            System.out.println("授权异常"+e.getMessage());
        }
        System.out.println("---------授权结束----------");
        return info;
    }

    //登录 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("---------进入登录认证---------");
        userService= SpringContextUtil.getBean(UserService.class);
        UsernamePasswordToken utoken = (UsernamePasswordToken) token;
        String username = utoken.getUsername();
        Session session = SecurityUtils.getSubject().getSession();
        User user = userService.userLogin(username);
        if (user == null) {
            throw new NullPointerException("账户或密码不正确，请重试");
        }
        ByteSource salt = ByteSource.Util.bytes(username);//加密盐
        //使用实现 方法创建对象，构造方法参数使用（用户名、密码、加密盐、当前方法名）
        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username, user.getPassword(), salt, this.getName());
        session.setAttribute("user", user);
        return authenticationInfo;
    }

}
